import os from 'os';
import fs from 'fs';
import { bootEvent } from '../boot';
import { makeLabelLogger } from '../util/logger';
import { container, Config, hredis } from '../app';
import { ISyncService, tsISyncService, SyncUserMessageType, SyncAdImageMessageType, SyncConfigMessageType } from '../service/api/sync';
import { IUserService, tsIUserService } from 'src/service/api/user';
import { rebuildFileList } from '../util/asset';

/*
这个文件里面都是用来处理从同步服务器接收的数据变化通知
*/

let { llog, lerror } = makeLabelLogger('syncuser');
let syncService: ISyncService;
let userService: IUserService;

bootEvent.on('appStart', () => {
	userService = container.get<IUserService>(tsIUserService);
	syncService = container.get<ISyncService>(tsISyncService);

	// 总配置改变，将其存到assets下面，同时刷新文件列表，客户端下次启动时会检测到更新
	syncService.onRemoteMessage(SyncConfigMessageType, action => {
		llog('updateDataConfig', action.data.length);
		let dir = Config.getStaticDirectory();
		fs.writeFileSync(`${dir}/assets/res/data.json`, action.data);
		rebuildFileList();
	});

	// 广告图改变，存到数据库里，每次客户端连接在线发给它们
	syncService.onRemoteMessage(SyncAdImageMessageType, action => {
		llog('updateAdImage', action.data);
		let key = `config:adImage`;
		hredis.set(key, action.data);
	});

	// 用户信息改变
	syncService.onRemoteMessage(SyncUserMessageType, action => {
		if (syncService.isOwnAction(action)) {
			llog('skip own action');
			return;
		}
		try {
			if (action.type == 'UpdateUser') {
				processUpdateUser(action);
				return;
			}

			llog('user action', action);
			if (action.type == 'NewUser') {
				processNewUser(action);
			}
			if (action.type == 'NewGuest') {
				processNewGuest(action);
			}
			if (action.type == 'UpdateViewNums') {
				processUpdateViewNums(action);
			}
		} catch (e) {
			lerror(e);
		}
	});
});

// 服务器通知用户信息改变
let processUpdateUser = async action => {
	// llog('sync update user', action.users.length);
	action.users.forEach(u => {
		llog('sync user', u.clientid);
	});
};

// 服务器通知新用户注册
let processNewUser = async action => {
	// userService.Register(action.id, action.info);
};

// 服务器通知新用户(游客)创建
let processNewGuest = async action => {
	userService.UpdateUser(action.id, action.info);
};

// 服务器通知某用户观看次数
let processUpdateViewNums = async action => {
	userService.updateViewNums(action.id, action.viewsNums, action.changeMax);
};
